﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ZedGraph;
using Nauka.engine;

namespace Nauka.GUI
{
    public partial class MainWindow : Form
    {
        private MainProgram mp;

        public MainWindow(MainProgram mp)
        {
            InitializeComponent();
            this.mp = mp;
            updateTables();
        }

        private void updateTables(){
            DataTable dt = mp.dbconn.GetHandHistoryAll();
            HHBindingSource.DataSource = dt;
            handHistoryDataGridView.DataSource = HHBindingSource;

            DataTable ds = mp.dbconn.GetPlayersAll();
            playersPlayersBindingSource.DataSource = ds;
            playersPlayersDataGridView.DataSource = playersPlayersBindingSource;

            DataTable dd = mp.dbconn.getDailyWinnings(mp.statsFilter.hero);
            analGeneralDayBindingSource.DataSource = dd;
            analGeneralDayDataGridView.DataSource = analGeneralDayBindingSource;
            analGeneralDayDataGridView.Select();

            DataTable dm = mp.dbconn.getMonthlyWinnings(mp.statsFilter.hero);
            analGeneralMonthBindingSource.DataSource = dm;
            analGeneralMonthDataGridView.DataSource = analGeneralMonthBindingSource;

            DataTable dy = mp.dbconn.getYearWinnings(mp.statsFilter.hero);
            analGeneralYearBindingSource.DataSource = dy;
            analGeneralYearDataGridView.DataSource = analGeneralYearBindingSource;

            long id = mp.dbconn.getHeroId(mp.statsFilter.hero);
            mp.dbconn.count_player_stats(id);
            DataTable analStatsDT = mp.dbconn.getPlayerStats(mp.statsFilter.hero);
            analStatsBindingSource.DataSource = analStatsDT;
            analStatsDataGridView.DataSource = analStatsBindingSource;

            mp.startHandsStats.count();
            DataTable analStartingDT = mp.startHandsStats.generateDataTable();
            analStartingBindingSource.DataSource = analStartingDT;
            analStartingDataGridView.DataSource = analStartingBindingSource;

            DataTable sessionsDT = mp.dbconn.getSessions();
            analSessionsBindingSource.DataSource = sessionsDT;
            analSessionsDataGridView.DataSource = analSessionsBindingSource;

            DataTable positionsDT = mp.dbconn.getPositionStats();
            analPositionsBindingSource.DataSource = positionsDT;
            analPositionsDataGridView.DataSource = analPositionsBindingSource;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog opendlg = new OpenFileDialog();
            opendlg.Filter = "TEXT Files (*.txt)|*.txt|All Files (*.*)|*.*";
            

            if (opendlg.ShowDialog() == DialogResult.OK)
            {
                FileInfo myFile = new FileInfo(opendlg.FileName);
                DirectoryInfo miDir = new DirectoryInfo(myFile.DirectoryName);
                string[] row = { miDir.FullName, myFile.Name };
                importFilesDataGridView.Rows.Add(row);
            }

        }

        private void impoerEmptyListButton_Click(object sender, EventArgs e)
        {
            importFilesDataGridView.Rows.Clear();
        }

        private void importAddFolderButton_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog opendlg = new FolderBrowserDialog();
            DirectoryInfo myDirInfo;

            if (opendlg.ShowDialog() == DialogResult.OK)
            {
                myDirInfo = new DirectoryInfo(opendlg.SelectedPath);
                FileInfo[] myFileInfo = myDirInfo.GetFiles();
                foreach (FileInfo fi in myFileInfo)
                {
                    string[] row = { myDirInfo.FullName, fi.Name };
                    importFilesDataGridView.Rows.Add(row);
                }
            }
        }

        private void importStartImportButton_Click(object sender, EventArgs e)
        {
            Parser parser = new Parser();
            int count_files = 0;
            int count_hands = 0;
            int duplicates = 0;
            int errors = 0;
            ArrayList games = new ArrayList();
            int hour_start = DateTime.Now.Hour;
            int min_start = DateTime.Now.Minute;
            int sec_start = DateTime.Now.Second;

            this.Enabled = false;
            foreach (DataGridViewRow dgvr in importFilesDataGridView.Rows)
            {
                games.Clear();
                count_files++;
                string file = (string)dgvr.Cells[0].Value + "\\" + (string)dgvr.Cells[1].Value;
                if (file == "\\")
                    break;
                try
                {
                    games = parser.parse(file);
                }
                catch (Exception)
                {
                    errors++;
                    continue;
                }
         
                foreach (Hand hands in games)
                {
                    try
                    {
                        mp.dbconn.InsertHandToDB(hands);
                    }
                    catch(Exception){
                        duplicates++;
                    }
                }
                count_hands += games.Count;
                string[] row = { DateTime.Now.ToString(), file, (count_hands - duplicates).ToString(), duplicates.ToString(), "0" };
                importImportedFilesDataGridView.Rows.Add(row);
                importFilesImportedLabel.Text = count_files.ToString();
                importHandsImportedLabel.Text = (count_hands-duplicates).ToString();
                importDuplicatesLabel.Text = duplicates.ToString();
            }
            importErrorsLabel.Text = errors.ToString();
            string TimeInString = "";
            int hour = DateTime.Now.Hour;
            int min = DateTime.Now.Minute;
            int sec = DateTime.Now.Second;

            hour -= hour_start;
            min -= min_start;
            sec -= sec_start;
            if (sec < 0)
                sec += 60;

            TimeInString = (hour < 10) ? "0" + hour.ToString() : hour.ToString();
            TimeInString += ":" + ((min < 10) ? "0" + min.ToString() : min.ToString());
            TimeInString += ":" + ((sec < 10) ? "0" + sec.ToString() : sec.ToString());
            importTimeLabel.Text = TimeInString;
            this.Enabled = true;
            updateTables();
        }
        private void analGeneralDayDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            int rows = analGeneralDayDataGridView.Rows.Count;
            

            if (analGeneralDayDataGridView.SelectedCells.Count > 0)
            {
                analGeneralChart.GraphPane.Title.Text = (string)analGeneralDayDataGridView.SelectedCells[0].Value;
                PointPairList ppl = mp.dbconn.getPoints((string)analGeneralDayDataGridView.SelectedCells[0].Value, "kfiatkos");
                analGeneralChart.GraphPane.CurveList.Clear();
                LineItem myCurve = analGeneralChart.GraphPane.AddCurve("Winnings", ppl, System.Drawing.Color.Red);
                myCurve.Symbol.IsVisible = false;
                myCurve.Line.Width = 3;
            }
            analGeneralChart.GraphPane.XAxis.Title.Text = "Hands";
            analGeneralChart.GraphPane.YAxis.Title.Text = "Winnings";
            analGeneralChart.AxisChange();
            analGeneralChart.Refresh();
            
        }

        private void analGeneralMonthDataGridView_SelectionChanged(object sender, EventArgs e)
        {

            if (analGeneralMonthDataGridView.SelectedCells.Count > 0)
            {
                analGeneralChart.GraphPane.Title.Text = (string)analGeneralMonthDataGridView.SelectedCells[0].Value;
                PointPairList ppl = mp.dbconn.getPoints((string)analGeneralMonthDataGridView.SelectedCells[0].Value, "kfiatkos");
                analGeneralChart.GraphPane.CurveList.Clear();
                LineItem myCurve = analGeneralChart.GraphPane.AddCurve("Winnings", ppl, System.Drawing.Color.Red);
                myCurve.Symbol.IsVisible = false;
                myCurve.Line.Width = 3;

            }
            analGeneralChart.GraphPane.XAxis.Title.Text = "Hands";
            analGeneralChart.GraphPane.YAxis.Title.Text = "Winnings";
            analGeneralChart.AxisChange();
            analGeneralChart.Refresh();
        }

        private void analGeneralYearDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (analGeneralYearDataGridView.SelectedCells.Count > 0)
            {
                analGeneralChart.GraphPane.Title.Text = (string)analGeneralYearDataGridView.SelectedCells[0].Value;
                PointPairList ppl = mp.dbconn.getPoints((string)analGeneralYearDataGridView.SelectedCells[0].Value, "kfiatkos");
                analGeneralChart.GraphPane.CurveList.Clear();
                LineItem myCurve = analGeneralChart.GraphPane.AddCurve("Winnings", ppl, System.Drawing.Color.Red);
                myCurve.Symbol.IsVisible = false;
                myCurve.Line.Width = 3;

            }
            analGeneralChart.GraphPane.XAxis.Title.Text = "Hands";
            analGeneralChart.GraphPane.YAxis.Title.Text = "Winnings";
            analGeneralChart.AxisChange();
            analGeneralChart.Refresh();
        }

        private void handHistoryDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (handHistoryDataGridView.SelectedCells.Count > 0)
            {
             //   DBConn dbconn = new DBConn();
                HTMLGenerator html_gen = new HTMLGenerator((long)Convert.ToInt64(handHistoryDataGridView.SelectedCells[5].Value), mp);
                HHwebBrowser.DocumentText = html_gen.generate_html_string("kfiatkos");

            }

        }

        private void configureStatsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StatisticsConfigurationWindow statsWindow = new StatisticsConfigurationWindow(mp);
            statsWindow.Visible = true;
        }

        private void playersPlayersDataGridView_SelectionChanged(object sender, EventArgs e)
        {

            if (playersPlayersDataGridView.SelectedCells.Count > 0)
            {
                string player = (string)playersPlayersDataGridView.SelectedRows[0].Cells[0].Value;
                long player_id = mp.dbconn.getHeroId(player);
                mp.dbconn.count_player_stats(player_id);
                DataTable dt = mp.dbconn.getPlayerStats(player);
                playerStatsBindingSource.DataSource = dt;
                playerStatsDataGridView.DataSource = playerStatsBindingSource;

                HTMLGenerator html_gen = new HTMLGenerator(mp);
                PlayerWebBrowser.DocumentText = html_gen.getHTMLPlayer(player);
            }
        }

        private void importFilesDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mp.end_program();
        }

        private void dBManagementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DBManagementWindow dbmw = new DBManagementWindow(mp);
            dbmw.Visible = true;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutWindow aw = new AboutWindow();
            aw.Visible = true;
        }

        private void analSessionsDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (analSessionsDataGridView.SelectedRows.Count > 0)
            {
                DateTime start = new DateTime();
                DateTime end = new DateTime();
                Console.WriteLine(analSessionsDataGridView.SelectedRows[0].Cells[1].Value.ToString());
                start = DateTime.ParseExact(analSessionsDataGridView.SelectedRows[0].Cells[1].Value.ToString(), "yyyy-MM-dd HH:mm:ss", null);
                end = DateTime.ParseExact(analSessionsDataGridView.SelectedRows[0].Cells[2].Value.ToString(), "yyyy-MM-dd HH:mm:ss", null);
                DataTable dt = mp.dbconn.GetHandHistorySessions(start, end);
                SessionsHHBindingSource.DataSource = dt;
                analSessionsHandsDataGridView.DataSource = SessionsHHBindingSource;
            }
        }

        private void analSessionsHandsDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (analSessionsHandsDataGridView.SelectedCells.Count > 0)
            {
                //   DBConn dbconn = new DBConn();
                HTMLGenerator html_gen = new HTMLGenerator((long)Convert.ToInt64(analSessionsHandsDataGridView.SelectedCells[5].Value), mp);
                sessionsHHWebBrowser.DocumentText = html_gen.generate_html_string("kfiatkos");

            }
        }
       
        private void analPositionsDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if(analPositionsDataGridView.SelectedRows.Count > 0){
                string pos = analPositionsDataGridView.SelectedRows[0].Cells[0].Value.ToString().Trim();
                DataTable dt = mp.dbconn.GetHandHistoryPositions(pos);
                analPosHandsBindingSource.DataSource = dt;
                analPosHandsDataGridView.DataSource = analPosHandsBindingSource;
            }
        }

        private void analPosHandsDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (analPosHandsDataGridView.SelectedCells.Count > 0)
            {
                //Console.WriteLine(analPosHandsDataGridView.SelectedRows[0].Cells[0].Value.ToString());
                HTMLGenerator html_gen = new HTMLGenerator((long)Convert.ToInt64(analPosHandsDataGridView.SelectedCells[5].Value), mp);
                positionHHWebBrowser.DocumentText = html_gen.generate_html_string(mp.statsFilter.hero);
            }
        }


    }
}
